package com.ruiyin.service;

import com.ruiyin.dao.AdminDao;
import com.ruiyin.entity.Admin;
import com.ruiyin.entity.AdminAccount;
import com.ruiyin.entity.App;
import com.ruiyin.entity.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Service
public class AdminService extends BaseService{
    @Autowired
    private AdminDao dao;
    private final Integer USE = 0;
    private final Integer UN_USE = 1;

    //0未设置 1测试卡 2周卡 3月卡 4年卡
    private final Integer TESTCARD = 1;
    private final Integer WEEK_CARD = 2;
    private final Integer MONTH_CARD = 3;
    private final Integer YEAR_CARD = 4;
    private final Integer FLAG = 0;


    public Integer queryIMEI(String imei) {
       return dao.query(imei);
    }

    @Transactional(rollbackFor = {Exception.class},readOnly = false)
    public void activity(String imei,Integer type,String flag) throws Exception {
        Admin admin = new Admin();
        int now = 0;

        switch (type){
            case 1:
                now = 1;
                break;
            case 2:
                now = 7;
                break;
            case 3:
                now = 30;
                break;
            case 4:
                now = 3650*60;
                break;
        }
        try {

            admin.setDateTime(setDate(now));
            admin.setType(type);
            admin.setStatus(USE);
            admin.setUpdateDate(getDate());
            admin.setImei(imei);
            admin.setFlag(flag);
            dao.update(admin);
        }catch (Exception e){
            throw new Exception("激活失败，请联系开发人员");
        }
    }

    public List<Valid> findAll() {
        return dao.queryAll();
    }

    @Transactional(rollbackFor = Exception.class,readOnly = false)
    public int reg(AdminAccount account) throws Exception {
        if(queryUser(account)){
            return 1;
        }
        try {
            dao.insert(account);
        } catch (Exception e) {
           throw new Exception("注册失败");
        }
        return 0;
    }

    public boolean queryUser(AdminAccount account){
        return dao.queryUser(account) == 1?true:false;
    }

    public int login(AdminAccount account) {
        if(!queryUser(account)){
            return -1;
        }

        return dao.checkLogin(account) == 1?0:1;
    }

    @Transactional(rollbackFor = Exception.class,readOnly = false)
    public void updateStatus(String imei,String status) {
        dao.updateStatus(imei,status);
    }

    public void insertUrl(App app) {
        dao.insertUrl(app);
    }
}
